//
//  DNKUdpRequestManager.m
//  XiangJia
//
//  Created by user on 16/7/26.
//  Copyright © 2016年 Dnake. All rights reserved.
//

#import "DNKUdpRequestManager.h"

#import "GCDAsyncUdpSocket.h"

#define P2P_CONTROL_IP @"255.255.255.255"

@interface DNKUdpRequestManager ()<GCDAsyncUdpSocketDelegate> {
    GCDAsyncUdpSocket *udpSocket;
}

@property (nonatomic, copy) UdpSendFailureBlock sendFailureBlock;
@property (nonatomic, copy) UdpSendSuccessBlock sendMessageSuccess;

@end

@implementation DNKUdpRequestManager

+ (DNKUdpRequestManager *)shareUdpManager
{
    static DNKUdpRequestManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DNKUdpRequestManager alloc] init];
    });
    return manager;
}

- (void)initWithPort:(NSInteger)port { 
    //初始化socket
    udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    
    NSError *error = nil;
    //广播只接收ipv4
    [udpSocket setIPv6Enabled:NO];
    [udpSocket setIPv4Enabled:YES];
    //绑定端口号
    [udpSocket bindToPort:port error:&error];
    if (error) {//监听错误打印错误信息
        NSLog(@"error:%@",error);
    }
    [udpSocket enableBroadcast:YES error:&error];
    if (error) {//监听错误打印错误信息
        NSLog(@"error:%@",error);
    }
    //接收
    [udpSocket beginReceiving:&error];
    if (error) {//监听错误打印错误信息
        NSLog(@"error:%@",error);
    }
    
    [udpSocket connectedPort];
}

- (void)connectBoardPort {
    if (udpSocket.isClosed) {
        [udpSocket connectedPort];
    } 
}

- (void)coloseUDP {
    [udpSocket close]; 
}

- (void)CallMessageSuccessBlock:(UdpSendSuccessBlock)successBlock
                   failureBlock:(UdpSendFailureBlock)failuerBlock {
    
    if (successBlock) {
        self.sendMessageSuccess = successBlock;
    }
    if (failuerBlock) {
        self.sendFailureBlock = failuerBlock;
    }
}
 
//控制命令
- (void)sendUdpWithData:(NSData *)data toIp:(NSString *)ip port:(NSInteger)port Timeout:(NSInteger)timeout tag:(NSInteger)tag {
    [udpSocket sendData:data toHost:ip port:port withTimeout:timeout tag:tag];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSelector:@selector(udpTimeOut) withObject:nil afterDelay:timeout];
    });
}

//广播发送数据
- (void)sendUdpBroadData:(NSData *)data port:(NSInteger)port Timeout:(NSInteger)timeout tag:(NSInteger)tag {
    [udpSocket sendData:data toHost:P2P_CONTROL_IP port:port withTimeout:timeout tag:tag];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self performSelector:@selector(udpTimeOut) withObject:nil afterDelay:10];
    });
}


//发送成功回调方法
//- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
//    NSLog(@"| SmartHomeSDK | - UDP服务段数据发送成功");
//}
//
//- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError * _Nullable)error {
//    NSLog(@"| didNotConnect | - UDP服务段数据发送失败 %@",error.localizedDescription);
//    self.sendFailureBlock(error.localizedDescription);
//}
////发送失败回调方法
//- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError *)error {
//    NSLog(@"| SmartHomeSDK | - UDP服务段数据发送失败 %@",error.localizedDescription);
//    self.sendFailureBlock(error.localizedDescription);
//}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{  
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(udpTimeOut) object:nil];
        
        //广播
        if (self.sendMessageSuccess) {
            self.sendMessageSuccess(data, address, -1);
        } 
        
    });
} 


/**
 *  超时处理
 */
-(void)udpTimeOut {
    //广播
    if (self.sendFailureBlock) {
        self.sendFailureBlock(@"发送数据超时");
    }
}

- (NSString *)hostFromAddress:(NSData *)address {
    return [GCDAsyncUdpSocket hostFromAddress:address];
}

@end





